package org.biogroovy.net

import groovy.json.JsonSlurper

import javax.xml.parsers.DocumentBuilderFactory

import org.w3c.dom.Element

public class URLFactory {

	/**
	 * This method creates an URL.
	 * @param urlType  A URL template.
	 * @param parameters  a map of parameters for the URL.
	 */
	public static String getURL(String urlType, Map parameters) {
		URLMap urlMap = new URLMap(urlType, parameters);
		return urlMap.toString();
	}

	/**
	 * This method gets the contents of the URL as XML.
	 * @param urlType  A URL template.
	 * @param parameters  a map of parameters for the URL.
	 * @return the root node of the XML document
	 */
	public static Element getURLasXML(String urlType, Map parameters){
		URL url = new URL(getURL(urlType, parameters));
		def builder     = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		return (Node)builder.parse(url.openStream())?.getDocumentElement();
	}
	
	/**
	 * This method gets the contents of the URL as a Map of properties from a JSON object.
	 * @param urlType a URL template
	 * @param parameters a map of parameters for the URL
	 * @return a map of properties.
	 */
	public static Object getURLasJSON(String urlType, Map parameters){
		URLMap urlMap = new URLMap(urlType, parameters);
		String urlStr = urlMap.toString();
		URL url = new URL(urlStr);
		JsonSlurper slurper = new JsonSlurper();
		return slurper.parse(url.openStream());
	}
}
